package com.ipzoe.web.core.beetl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.google.common.collect.Maps;
import com.ipzoe.common.utils.spring.SpringContextHolder;
import org.beetl.core.Context;
import org.beetl.core.Function;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class GetWebUrl implements Function {

    @Override
    public Object call(Object[] objects, Context context) {
        HttpServletRequest request = (HttpServletRequest)objects[0];
        String queryKey = String.valueOf(objects[1]);
        String value =  String.valueOf(objects[2]);

        return getUrl(request, queryKey, value);
    }

    public String getUrl(HttpServletRequest request, String queryKey, String value){

        Map<String, String> paramMap = Maps.newHashMap();
        Enumeration<String> parameterNames = request.getParameterNames();
        while(parameterNames.hasMoreElements()){
            String paramName = parameterNames.nextElement();
            if(!"pg".equals(queryKey) && "pg".equals(paramName)){
                continue;
            }
            paramMap.put(paramName, request.getParameter(paramName));
        }
        if(!StrUtil.hasEmpty(queryKey, value) && !"all".equalsIgnoreCase(value)){
            paramMap.put(queryKey, value);
        }else if(!StrUtil.hasEmpty(queryKey, value) && "all".equalsIgnoreCase(value)){
            paramMap.remove(queryKey);
        }
        String queryString = URLUtil.buildQuery(paramMap, Charset.forName("UTF-8"));

        String activeProfile = SpringContextHolder.getApplicationContext().getEnvironment().getActiveProfiles()[0];
        String url = request.getRequestURL().toString();
        if ("prod".equals(activeProfile)) {
            url = url.replace("http://","https://");
        }

        return StrUtil.isEmpty(queryString) ? url : url + "?" + queryString;
    }

}
